package org.example.modules.oss.controller;

import org.example.common.utils.R;
import org.example.modules.oss.service.FileService;
import org.example.modules.sys.dto.FileDto;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.support.StandardMultipartHttpServletRequest;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.IOException;
import java.io.OutputStream;
import java.util.Iterator;
import java.util.UUID;

@RestController
@RequestMapping("/oss/file")
public class FileController {
    @Autowired
    FileService fileService;

    @PostMapping("/upload")
    public R upload(MultipartFile file) throws IOException {
        System.out.println("upload--file is"+file);
        //调用service中的业务方法
        FileDto fileDto = fileService.upload(file);
        return R.ok().put("data",fileDto);
    }

    @GetMapping("/download")
    public Object downloadFile(HttpServletResponse response, String filePath) throws IOException {
        // 清空输出流
        response.reset();
        response.setContentType("application/x-download;charset=UTF-8");
        response.setHeader("Content-Disposition", "attachment;filename="+ new String(filePath.getBytes("utf-8"), "utf-8"));
        fileService.download(response.getOutputStream(),filePath);
        return null;
    }

    @RequestMapping("/wx-upload")
    public R wxUpload(@RequestParam("file") MultipartFile file) throws Exception{
        if(!file.isEmpty()){
            FileDto fileDto = fileService.upload(file);
            return R.ok().put("data",fileDto);
        }
        else return R.error();
    }

}
